package service

import (
	"../model"
	"../utils"
	"errors"
	"fmt"
	"math/rand"
	"time"
)

type UserService struct {
}

/**
 * 注册
 */
func (userService *UserService) Register(
	mobile, plainPasswd, nickName, avatar, sex string) (user model.MobileUser, err error) {

	// 检测手机号码是否已注册
	user = model.MobileUser{}
	_, err = DBEngine.Where("mobile = ?", mobile).Get(&user)
	if err != nil {
		return user, err
	}

	if user.Id > 0 {
		return user, errors.New("该手机号已注册.")
	}

	// 插入新用户
	user.Avatar = avatar
	user.Mobile = mobile
	user.Nickname = nickName
	user.Sex = sex
	user.Salt = fmt.Sprintf("%06d", rand.Int31n(1000000))
	user.Passwd = utils.ComputePasswd(plainPasswd, user.Salt)
	user.CreateAt = time.Now()

	affectedRows, err := DBEngine.InsertOne(&user)
	if err != nil {
		return user, err
	}

	if affectedRows <= 0 {
		return user, errors.New("新建用户失败.")
	}

	return user, nil
}

/**
 * 登录
 */
func (userService *UserService) Login(mobile, plainPasswd string) (user model.MobileUser, err error) {

	user = model.MobileUser{}
	// 根据主键查询用户
	isExist, err := DBEngine.Alias("u").Where("u.mobile = ?", mobile).Get(&user)
	if err != nil {
		return user, err
	}

	if !isExist {
		return user, errors.New("该手机号账户不存在.")
	}

	if user.Passwd != utils.ComputePasswd(plainPasswd, user.Salt) {
		return user, errors.New("用户名或密码错误.")
	}

	// 生成Token
	strToken := fmt.Sprintf("%d", time.Now().Unix())
	user.Token = utils.Sha256(strToken)

	affectedRows, err := DBEngine.ID(user.Id).Cols("token").Update(&user)
	if err != nil {
		return user, err
	}

	if affectedRows <= 0 {
		return user, errors.New("更新token失败.")
	}
	return user, nil
}
